package com.cy.pj.sys.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.cy.pj.common.vo.PageResult;
import com.cy.pj.exception.ServiceException;
import com.cy.pj.sys.dao.SysMemberDao;
import com.cy.pj.sys.dao.SysOrderDao;
import com.cy.pj.sys.entity.SysMember;
import com.cy.pj.sys.entity.SysOrder;
import com.cy.pj.sys.service.SysOrderService;

@Service
public class SysOrderServiceImpl implements SysOrderService{

	@Autowired
	private SysOrderDao sysOrderDao;
	
	@Autowired
	private SysMemberDao sysMemberDao;
	
	
	
	@Override
	public PageResult<SysOrder> findPageObjects(String memberName, Integer pageCurrent) {
		// 校验参数
		if(pageCurrent==0 || pageCurrent<1)
			throw new IllegalArgumentException("请输入正确的页码值");
		
		// 查询总数
		int rowCount = sysOrderDao.getRowCount(memberName);
		
		if(rowCount==0) 
			throw new ServiceException("所有订单已处理");
		 
		
		// 分页查询
		int pageSize = 3;
		int startIndex = (pageCurrent-1)*pageSize;
		List<SysOrder> records=
				sysOrderDao.findPageObjects(memberName, startIndex, pageSize);
		
		// 封装
		PageResult<SysOrder> list = new PageResult<>();
		list.setPageCount( (rowCount-1)/pageSize+1 );
		list.setPageCurrent(pageCurrent);
		list.setPageSize(pageSize);
		list.setRecords(records);
		list.setRowCount(rowCount);
		
		return list;
	}

	@Override
	public void saveOrderInfo(SysOrder sysOrder) {
		sysOrder.setPayTime(new Date());
		
		sysOrderDao.insertOrderInfo(sysOrder);
	}

	@Override
	public SysOrder findOrderById(Integer id) {
		SysOrder entity = sysOrderDao.selecyOrderById(id);
		
		return entity;
	}
	
	@Transactional
	@Override
	public int payOrderById(Long itemPrice, Integer id,String memberMobile) {
		
		if(StringUtils.isEmpty(itemPrice))
			throw new ServiceException("请输入商品价格");
			
		// 获取会员余额
		SysMember member = 
				sysMemberDao.selectMemberByMobile(memberMobile);
		Long account = member.getAccount();
		
		// 支付之后的余额
		Long newAccount = account-itemPrice;
		if(newAccount < 0)
			throw new ServiceException("余额不足，请充值!"); 
		
		// 更新会员账户余额，并删除订单
		int rows1 =
				sysMemberDao.updateAccountByMobile(newAccount, memberMobile);
		if(rows1==0)
			throw new ServiceException("支付失败！");
		
		int rows = sysOrderDao.deleteOrderById(id);
		if(rows1==0)
			throw new ServiceException("支付失败！");
		
		return rows;
	}

	@Override
	public void deleteOrderById(Integer id) {
		
		sysOrderDao.deleteOrderById(id);
		
	}

	
	
	
}
